/**
 * @desc 公共工具
 */

const Util = {
  /**
   * 设置Cookie
   * @param {string} name 设置的Cookie属性
   * @param {string} val  设置的Cookie值
   * @param {string} path 设置的Cookie的路径
   * @param {number} date 设置的Cookie的过期时间(天数)
   */
  setCookie(name, val, path, date) {
    const oDate = new Date()
    oDate.setDate(oDate.getDate() + (date || 30))
    const sDate = `;expires=${oDate}`
    const Path = `;path=${path || '/'}`
    document.cookie = `${name}=${val}${sDate}${Path}`
  },

  /**
   * 获取Cookie
   * @param   {string} name 需要获取的Cookie属性
   * @returns {string} 获取到的Cookie值
   */
  getCookie(name) {
    const sCookies = document.cookie
    const arr = sCookies.split('; ')

    for (let i = 0; i < arr.length; i++) {
      const arr2 = arr[i].split('=')
      if (arr2[0] === name) {
        return arr2[1]
      }
    }

    return ''
  },

  /**
   * 删除Cookie
   * @param {string} name 需要删除的Cookie
   */
  delCookie(name) {
    this.setCookie(name, '', '', -1)
  },

  /**
   * 获取Cookie的个数
   * @returns {number} Cookie的个数
   */
  cookieLength() {
    const sCookie = document.cookie
    const arr = sCookie.split('; ')
    if (!sCookie) {
      return 0
    }
    return arr.length
  },

  /**
   * 设置加载层
   * @returns options 加载层的属性
   */
  loadingOptions(text) {
    const options = {
      lock: false,
      text: text || '正在加载',
    }
    return options
  },
  /**
   * 时间戳转换为yyyy-MM-dd hh：mm：ss
   */
  // 时间处理
  formatDateTime(inputTime) {
    const date = new Date(inputTime)
    const y = date.getFullYear()
    let m = date.getMonth() + 1
    m = m < 10 ? (`0${m}`) : m
    let d = date.getDate()
    d = d < 10 ? (`0${d}`) : d
    let h = date.getHours()
    h = h < 10 ? (`0${h}`) : h
    let minute = date.getMinutes()
    let second = date.getSeconds()
    minute = minute < 10 ? (`0${minute}`) : minute
    second = second < 10 ? (`0${second}`) : second
    return `${y}-${m}-${d} ${h}:${minute}:${second}`
  },
  stringToByte(str) {
    const bytes = new Array()
    let len,
      c
    len = str.length
    for (let i = 0; i < len; i++) {
      c = str.charCodeAt(i)
      if (c >= 0x010000 && c <= 0x10FFFF) {
        bytes.push(((c >> 18) & 0x07) | 0xF0)
        bytes.push(((c >> 12) & 0x3F) | 0x80)
        bytes.push(((c >> 6) & 0x3F) | 0x80)
        bytes.push((c & 0x3F) | 0x80)
      } else if (c >= 0x000800 && c <= 0x00FFFF) {
        bytes.push(((c >> 12) & 0x0F) | 0xE0)
        bytes.push(((c >> 6) & 0x3F) | 0x80)
        bytes.push((c & 0x3F) | 0x80)
      } else if (c >= 0x000080 && c <= 0x0007FF) {
        bytes.push(((c >> 6) & 0x1F) | 0xC0)
        bytes.push((c & 0x3F) | 0x80)
      } else {
        bytes.push(c & 0xFF)
      }
    }
    return bytes
  },
}

export default Util
